﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace DE.Sdc.SharePoint.Common.Deployment.FileExtensionActions
{
    public class FileExtensionActionDictionary
    {
        private Dictionary<SupportedFileExtension, IFileExtensionAction> _fileExtensionActions;
        private Dictionary<string, SupportedFileExtension> _supportedFileExtensions;

        public FileExtensionActionDictionary()
        {
            _fileExtensionActions = new Dictionary<SupportedFileExtension, IFileExtensionAction>();
            _supportedFileExtensions = new Dictionary<string, SupportedFileExtension>();
        }

        public void Add(Type fileExtensionActionType, SPFeatureReceiverProperties properties)
        {
            IFileExtensionAction fileExtensionAction = (IFileExtensionAction) Activator.CreateInstance(fileExtensionActionType);
            fileExtensionAction.FeatureReceiverProperties = properties;

            object[] supportedFileExtensions = fileExtensionActionType.GetCustomAttributes(typeof(SupportedFileExtension), true);

            for (int i = 0; i < supportedFileExtensions.Length; i++)
            {
                SupportedFileExtension supportedFileExtension = (SupportedFileExtension)supportedFileExtensions[i];
                _fileExtensionActions.Add(supportedFileExtension, fileExtensionAction);

                if (!_supportedFileExtensions.ContainsKey(supportedFileExtension.FileExtension.ToLowerInvariant()))
                    _supportedFileExtensions.Add(supportedFileExtension.FileExtension.ToLowerInvariant(), supportedFileExtension);
            }
        }

        public void Execute(Item itemDefinition, SPFile file)
        {
            if (file == null)
                return;

            string lowerCasedFileExtension = Path.GetExtension(file.Name).ToLowerInvariant();
            if (_supportedFileExtensions.ContainsKey(lowerCasedFileExtension))
            {
                foreach (var fileExtensionAction in _fileExtensionActions)
                {
                    if (fileExtensionAction.Key.FileExtension.ToLower() == lowerCasedFileExtension)
                    {
                        if (fileExtensionAction.Key.ExecuteForEachFile)
                            fileExtensionAction.Value.ExecuteAction(itemDefinition, file);
                    }
                }
            }
        }

        public void Execute()
        {
            //foreach (var fileExtensionAction in _fileExtensionActions)
            //{
            //    if (!fileExtensionAction.Key.ExecuteForEachFile)
            //        fileExtensionAction.Value.ExecuteAction();
            //}
        }
    }
}
